package test.task.fun.view;

import java.util.List;

import test.task.fun.R;
import test.task.fun.model.Goods;
import test.task.fun.model.GoodsPosition;
import test.task.fun.service.GoodsStore;
import test.task.fun.view.util.ScrollView;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

public class BuyActivity extends Activity {

	private GoodsStore goodsStore;
	private ScrollView pageSlider;
	private View buyButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.e("buyActivity", "create");
		setContentView(R.layout.act_buy);
		goodsStore = GoodsStore.getInstance(getApplicationContext());
		pageSlider = (ScrollView) findViewById(R.id.scroll);
		pageSlider.getRootLayout().removeAllViews();

		goodsStore.setOnGoodsCreateHandler(onGoodsCreateHandler);
		goodsStore.setOnGoodsRemovedHandler(onGoodsRemovedHandler);
		goodsStore.setOnGoodsQuantityChangedHandler(onGoodsQuantityChangedHandler);

		buyButton = findViewById(R.id.act_buy_btn);

	}

	@Override
	protected void onStart() {
		super.onStart();
		pageSlider.getRootLayout().removeAllViews();
		goodsStore.loadGoodsFromStorage(initHandler);
	}

	/**
	 * Отложили инициализацию списка, чтобы не было задержки при первой
	 * отрисовке активити
	 */
	private final Handler initHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			List<GoodsPosition> positions = (List<GoodsPosition>) msg.obj;
			for (GoodsPosition position : positions) {
				LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				LinearLayout view = (LinearLayout) inflater.inflate(R.layout.page, null);
				view.setTag(position.getGoods());
				pageSlider.getRootLayout().addView(view);
				initView(position, view);
			}
			chageButtonVisibility();

		}

	};

	private final Handler onGoodsCreateHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Goods goods = (Goods) msg.obj;
			GoodsPosition position = new GoodsPosition();
			position.setGoods(goods);
			position.setQuantity(1);
			LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			LinearLayout view = (LinearLayout) inflater.inflate(R.layout.page, null);
			view.setTag(goods);
			pageSlider.getRootLayout().addView(view);
			initView(position, view);
			chageButtonVisibility();

		}

	};
	private final Handler onGoodsQuantityChangedHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			GoodsPosition goodsPosition = (GoodsPosition) msg.obj;
			View view = getViewByGoods(goodsPosition.getGoods());
			initView(goodsPosition, view);

		}

	};

	private final Handler onGoodsRemovedHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Goods goods = (Goods) msg.obj;
			pageSlider.getRootLayout().removeView(getViewByGoods(goods));
			chageButtonVisibility();
			changeActivePageIndex();

		}

	};

	private View getViewByGoods(Goods goods) {
		for (int i = 0; i < pageSlider.getRootLayout().getChildCount(); i++) {
			View child = pageSlider.getRootLayout().getChildAt(i);
			if (child.getTag().equals(goods)) {
				return child;
			}

		}
		return null;

	}

	public void buy(View view) {
		if (pageSlider.getActivePageIndex() < pageSlider.getRootLayout().getChildCount()) {
			View child = pageSlider.getRootLayout().getChildAt(pageSlider.getActivePageIndex());
			goodsStore.buyGoods((Goods) child.getTag());
		}

	}

	private void initView(GoodsPosition goodsPosition, View view) {
		TextView name = (TextView) view.findViewById(R.id.act_buy_name);
		name.setText(goodsPosition.getGoods().getName());

		TextView type = (TextView) view.findViewById(R.id.act_buy_type);
		type.setText(goodsPosition.getGoods().getType().getResourceId());

		TextView price = (TextView) view.findViewById(R.id.act_buy_price);
		price.setText(goodsPosition.getGoods().getPrice().toString());

		TextView quantity = (TextView) view.findViewById(R.id.act_buy_quantity);
		quantity.setText(goodsPosition.getQuantity().toString());

	}

	/**
	 * Когда нет ни одного товара на продажу, скрываем кнопку купить
	 */
	private void chageButtonVisibility() {
		if (pageSlider.getRootLayout().getChildCount() > 0) {
			buyButton.setVisibility(View.VISIBLE);
		} else {
			buyButton.setVisibility(View.INVISIBLE);
		}

	}

	/**
	 * Удалили крайний правый товар из списка, нужно сдвинуть индекс страницы
	 */
	private void changeActivePageIndex() {
		if (pageSlider.getActivePageIndex() > pageSlider.getRootLayout().getChildCount() - 1) {
			pageSlider.setActivePageIndex(pageSlider.getRootLayout().getChildCount() - 1);
		}

	}

}
